package com.cqeec.myblog.controller;

import java.io.IOException;
import java.io.PrintWriter;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.cqeec.myblog.model.Blogger;
import com.cqeec.myblog.service.AlbumService;
import com.cqeec.myblog.service.AlbumServiceImpl;

@WebServlet("/app/album/management.html")
public class AlbumManagementServlet extends HttpServlet {
	private static final long serialVersionUID = 3052265148056398968L;
	private AlbumService albumService = new AlbumServiceImpl();

	@Override
	protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
		String method = req.getParameter("m");
		if ("create".equals(method)) {
			// 创建相册
			req.getRequestDispatcher("create.jsp").forward(req, resp);
		} else if ("save".equals(method)) {
			// 保存相册
			String name = req.getParameter("name");
			name = new String(name.getBytes("ISO-8859-1"), "UTF-8");
			String description = req.getParameter("description");
			description = new String(description.getBytes("ISO-8859-1"), "UTF-8");
			// 从会话中获取当前博主的标识
			Object obj = req.getSession().getAttribute("blogger");
			Blogger blogger;
			if (obj != null) {
				blogger = (Blogger) obj;
				try {
					albumService.saveAlbum(blogger.getId(), name, description);
					resp.sendRedirect("index.html");
				} catch (Exception e) {
					e.printStackTrace();
				}
			}
		} else if ("update".equals(method)) {
			resp.setCharacterEncoding("UTF-8");
			// 更新相册信息
			String id = req.getParameter("id");
			String name = req.getParameter("name");
			String desc = req.getParameter("desc");
			int code; // 状态码，表示操作是否成功（0，成功；1，失败。）
			String message; // 消息
			PrintWriter out = resp.getWriter(); // response对象的输出流
			try {
				albumService.updateAlbum(id, name, desc);
				code = 0;
				message = "相册信息更新成功！";
			} catch (Exception e) {
				code = 1;
				message = "相册信息更新失败！";
				e.printStackTrace();
			}
			out.write("{\"code\":" + code + ",\"message\":\"" + message + "\"}");
		} else if ("del".equals(method)) {
			// 删除相册
			resp.setCharacterEncoding("UTF-8");
			String albumId = req.getParameter("id");
			int code;
			String message;
			PrintWriter out = resp.getWriter();
			try {
				albumService.deleteAlbum(albumId);
				code = 0;
				message = "删除相册成功！";
			} catch (Exception e) {
				code = 1;
				message = "删除相册失败！";
				e.printStackTrace();
			}
			out.write("{\"code\":" + code + ",\"message\":\"" + message + "\"}");
		}
	}

	@Override
	protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
		doPost(req, resp);
	}

}
